package com.schrodinger.aop.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by zhangli on 2017/9/19.
 */
public class CGLIBProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz) {
        //设置父类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy methodproxy) throws Throwable {
        System.out.println("start-->>");
        //通过代理类调用父类中的方法
        Object result = methodproxy.invokeSuper(obj, args);
        System.out.println("success-->>");
        return result;
    }

}
